var express = require('express');
var app = express();
var fs = require("fs");
var multer  = require('multer');
/** 
 * 下面的HTML代码创建一个文件上传表单。这种形式的方法属性设置为POST，以及enctype属性设置为 multipart/form-data
 * */ 
app.use(express.static('public'));
app.use(express.urlencoded({ extended: false }));
var upload = multer({dest: "/tmp/"});
app.use(upload.any())
// app.use(multer({ dest: '/tmp/'}));
// var storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//     cb(null, __dirname+'/tmp/')
//     },
//     filename: function (req, file, cb) {
//     cb(null, file.originalname);
//     }
//     });
//     //......
// app.use(storage.array('img',5));//多文件上传模式

app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})

app.post('/file_upload', function (req, res) {
    console.log("req.files.file: ",req.files[0])
    console.log("filename", req.files[0].originalname)
    console.log("path", req.files[0].path)
   var file = __dirname + "/" + req.files[0].originalname;
   fs.readFile( req.files[0].path, function (err, data) {
        fs.writeFile(file, data, function (err) {
         if( err ){
              console.log( err );
         }else{
               response = {
                   message:'File uploaded successfully',
                   filename:req.files[0].originalname
              };
          }
          console.log( response );
          res.end( JSON.stringify( response ) );
       });
   });
})

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

})

